<template>
  <div class="map_wrapper p_relative" style="overflow: hidden" >
    <!--    地图-->
    <div id="map" class="w-100 h-100 p_relative":style="{height:clientHeight+'px'}"></div>
    <div id="anchor"><img src="static/image/map/marker_click.png" alt="锚点"/></div>

    <div class="logo p_absolute cursor_p" style="left: 0;top:0">
      <div class="d-flex justify-content-center align-items-center ur-btn btn_back p_absolute" style="left: 0;top:0;" @click="fetch.toPage('dashboard')"><i class="iconfont icon-back"></i>返回</div>
      <div class="d-flex justify-content-center align-items-center ur-btn btn_back p_absolute" style="right: 0;top:0;" @click="drawFun"><i class="iconfont iconxuankuang"></i>{{!isDraw?'框选':'取消框选'}}</div>
    </div>

    <el-popover placement="bottom" width="400"  trigger="click" v-model="showPopover">
      <!--    搜索结果：集中器、灯杆-->
      <div class="px-3 py-2">
        <title-mark class="w-100 mb-3" :title="'集中器'"></title-mark>
        <el-select class="w-100" v-model="boxId" @change="popoverBoxChange">
          <el-option :key="'box'+index" :label="item.Name" :value="item.BoxId" v-for="(item,index) in searchBoxs"></el-option>
        </el-select>
        <title-mark class="w-100 mt-3 mb-2" :title="'灯杆'"></title-mark>
        <el-select class="w-100" v-model="poleId"  @change="popoverPoleChange">
          <el-option :key="'pole'+index" :label="item.PoleNo" :value="item.PoleId" v-for="(item,index) in searchPoles"></el-option>
        </el-select>
      </div>
      <el-input slot="reference" class="search_input p_absolute w400 font20" v-model="searchTxt" style="left: 24px;top:90px;" placeholder="请输入搜索内容" size="small">
        <el-button slot="append" class="ur-btn ur-btn-search" style="width: 56px;" @click.stop="searchDevs"><i class="iconfont icon-sousuo mr-0"></i></el-button>
      </el-input>
    </el-popover>

    <!--树搜索 ,statisticDialog=false-->
    <el-input class="tree_input p_absolute w400" v-model="regionName" style="left: 24px;top:151px;" size="small" disabled>
      <el-button slot="append" class="ur-btn" @click="showAreaTree=!showAreaTree,statisticDialog=false"><i class="iconfont icon-zhankai mr-0 txt_blue2" :class="{'rotate180':!showAreaTree}"  style="font-size: 25px;"></i></el-button>
    </el-input>

    <!-- 树目录-->
    <div v-show="showAreaTree" class="p_absolute tree_wrap " style="top:235px;left: 24px;">
      <el-input placeholder="输入关键字进行过滤" v-model="filterRegion"></el-input>
      <div class="scrollY mt-3" style="height: 510px;">
        <el-tree ref="tree" :data="treeData" :props="treeProps" @node-click="handleNodeClick" node-key="Id" default-expand-all
                 highlight-current :filter-node-method="filterNode"></el-tree>
      </div>
    </div>

    <!--数据统计、一键控制按钮-->
    <div class="p_absolute d-flex" style="left: 24px;bottom:60px;">
      <el-button class="ur-btn ur-btn-primary-large" :class="{active:statisticDialog}" @click="statisticFun">数据统计</el-button>
      <el-button class="ur-btn ur-btn-primary-large ml-4" :class="{active:oneCtrlDialog}" @click="oneCtrlFun">一键控制</el-button>
    </div>

    <div class="p_absolute d-flex" style="right: 24px;bottom:60px;">
      <el-button class="ur-btn ur-btn-primary-large" :class="{active:devImgDialog}" @click="devImgDialog=!devImgDialog">图例说明</el-button>
      <el-button class="ur-btn ur-btn-primary-large ml-4" @click="showBoxOverlay=!showBoxOverlay">{{showBoxOverlay?'集中器隐藏':'集中器全显'}}</el-button>
      <el-button class="ur-btn ur-btn-primary-large ml-4" @click="showLightOverlay=!showLightOverlay">{{showLightOverlay?'灯杆隐藏':'灯杆全显'}}</el-button>
    </div>
    <!--版权copyright.png-->
  <!--  <div class="copyrightWrapper">
      <div class="copyright"></div>
    </div>-->


    <!--一键控制-->
    <div v-ur-drag-dialog v-if="oneCtrlDialog" ref="boxDialog" class="ur-dialog p_absolute" style="width: 400px;right: 24px;top:120px;">
      <div class="ur-dialog_header text-white ">集中器
        <el-button  class="ur-btn float-right">
          <i class="iconfont icon-close mr-0" @click="oneCtrlDialog=false"></i>
        </el-button>
      </div>
      <div class="ur-dialog_body">
        <one-ctrl :selBoxs="selBoxs" @setMapCenter="setMapCenter($event)"></one-ctrl>
      </div>
    </div>

    <!--    单灯控制-->
    <div v-ur-drag-dialog v-if="lightCtrlDialog" ref="poleDialog" class="ur-dialog p_absolute" style="width: 400px;right: 24px;top:120px;">
      <div class="ur-dialog_header text-white">单灯
        <el-button class="ur-btn float-right">
          <i @click="lightCtrlDialog=false" class="iconfont icon-close mr-0"></i>
        </el-button>
      </div>
      <div class="ur-dialog_body">
        <light-ctrl :selPole="pole" :poleImg="poleImg"></light-ctrl>
      </div>
    </div>

    <!--集中器-->
    <div v-ur-drag-dialog v-if="eccCtrlDialog" ref="boxDialog2" class="ur-dialog p_absolute" style="width: 400px;right: 24px;top:120px;">
      <div class="ur-dialog_header text-white">集中器
        <el-button class="ur-btn float-right">
          <i @click="eccCtrlDialog=false" class="iconfont icon-close mr-0"></i>
        </el-button>
      </div>
      <div class="ur-dialog_body">
        <ecc-ctrl :box="box"></ecc-ctrl>
      </div>
    </div>

    <!--能耗-->
    <div v-ur-drag-dialog v-if="statisticDialog" ref="poleDialog" class="ur-dialog p_absolute" style="width: 400px;right: 24px;top:120px;">
      <div class="ur-dialog_header text-white d-none"></div>
      <div class="ur-dialog_body">
        <data-statistic :regionIds="[regionId]"></data-statistic>
      </div>
    </div>

    <!--统计-->
    <div v-ur-drag-dialog v-if="statisticDialog" ref="poleDialog" class="ur-dialog p_absolute" style="width: 400px;top:218px;left: 24px;">
      <div class="ur-dialog_header text-white d-none"></div>
      <div class="ur-dialog_body">
        <device-statistics :regionIds="[regionId]"></device-statistics>
      </div>
    </div>

    <!--图例说明-->
    <div v-ur-drag-dialog v-if="devImgDialog" ref="boxDialog2" class="ur-dialog p_absolute" style="width: 380px;right: 20px;bottom:120px;">
      <div class="ur-dialog_header text-white">图例说明
        <el-button class="ur-btn float-right">
          <i @click="devImgDialog=false" class="iconfont icon-close mr-0"></i>
        </el-button>
      </div>
      <div class="ur-dialog_body pl-3 py-3 devImgDialog">
        <title-mark class="mb-2" :title="'灯'"></title-mark>
        <ul class="d-flex mt-3 poleImgGroup w-100">
          <li><img src="~static/image/map/pole/max/bulb_0.png"><label>关</label></li>
          <li><img src="~static/image/map/pole/max/bulb_1.png"><label>开</label></li>
          <li><img src="~static/image/map/pole/max/bulb_2.png"><label>故障</label></li>
          <li><img src="~static/image/map/pole/max/bulb_3.png"><label>不存在</label></li>
          <li><img src="~static/image/map/pole/max/bulb_4.png"><label>超时</label></li>
        </ul>
        <title-mark class="mt-3 mb-2" :title="'集中器'"></title-mark>
        <ul class="boxImgGroup d-flex w-100">
          <li><img src="~static/image/map/box/max/box_0.png"><label>离线</label></li>
          <li><img src="~static/image/map/box/max/box_1.png"><label>在线</label></li>
        </ul>
      </div>
    </div>

  </div>
</template>

<script>
  import api from 'api/api'
  import fetch from 'api/fetch'
  import elDragDialog from 'directive/el-dragDialog'
  import {mapState} from 'vuex'
  import oneCtrl from './one-ctrl'
  import eccCtrl from './ecc-ctrl/index'
  import lightCtrl from './light-ctrl'
  import dataStatistic from './statistics/data-statistics'
  import DeviceStatistics from './statistics/device-statistics'
  import urDragDialog from 'directive/ur-dragDialog'
  import titleMark from "base/titleMark"

  let boxVectorSource, boxVectorLayer,poleVectorSource, poleVectorLayer
  let mapMarks=[],selBoxMarks=[],selPoleMarks=[]
  let selBoxMarker=null,selPoleMarker=null
  let boxMap=new Map(),poleMap =new Map()
  let boxImgMap,poleImgMap
  let map,overall_lastfeature,activeMarker
  let googleLayer_map = 'http://map.geoq.cn/arcgis/rest/services/ChinaOnlineStreetPurplishBlue/MapServer/tile/{z}/{y}/{x}'
  // let googleLayer_map = 'http://map.geoq.cn/arcgis/rest/services/ChinaOnlineStreetGray/MapServer/tile/{z}/{y}/{x}'
  let layerTitle = new ol.layer.Tile({
    source: new ol.source.XYZ({
      url: googleLayer_map ,//谷歌地图
      // url:'http://webrd01.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scale=1&style=7'//7,8
      // url: 'http://wprd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&style=7&x={x}&y={y}&z={z}',
      // url : 'http://www.google.cn/maps/vt?pb=!1m5!1m4!1i{z}!2i{x}!3i{y}!4i256!2m3!1e0!2sm!3i342009817!3m9!2szh-CN!3sCN!5e18!12m1!1e47!12m3!1e37!2m1!1ssmartmaps!4e0&token=32965'
    }),
    // projection: 'EPSG:3857'
  })
  let drawInteraction,drawing=false
  let drawVector = new ol.layer.Vector({
    source: new ol.source.Vector(),
    style: new ol.style.Style({
      stroke: new ol.style.Stroke({color: '#43E2FF', width: 2,lineDash:[1,2,3,4,5,6]}),
      fill: new ol.style.Fill({color: 'rgba(210,227,10,0.2)'})
    })
  });

  let drawVector2 = new ol.layer.Vector({
    source:  new ol.source.Vector({
      projection: 'EPSG:3857',
      url: 'static/geojson/china.json', //从文件加载边界等地理信息
      format: new ol.format.GeoJSON({
        extractStyles: false
      })
    }),
    opacity:0.4,
    style: new ol.style.Style({
      fill: new ol.style.Fill({ //矢量图层填充颜色，以及透明度
        color: 'rgba(9,43,147,1)'//rgba(1,0,37,0.9)
      }),
      stroke: new ol.style.Stroke({color: '#319FD3', width: 1,lineDash:[1,2,3,4,5,6]}),
      text: new ol.style.Text({ //文本样式
        font: '12px Calibri,sans-serif',
        fill: new ol.style.Fill({color: '#e61f51'}),
        stroke: new ol.style.Stroke({color: '#fff', width: 3}),
        text:''
      }),
     /* geometry: function(feature) {
        var coordinates = feature.getGeometry().getCoordinates()[0];
        return new ol.geom.MultiPoint(coordinates);
      }*/
    })
  });

  export default {
    directives:{elDragDialog,urDragDialog},
    components: {DeviceStatistics, dataStatistic,oneCtrl,eccCtrl,lightCtrl,DeviceStatistics,titleMark},
    props: {},
    data() {
      return {
        fetch:fetch,
        searchTxt:'',
        regionName:'',
        regionId:null,
        oneCtrlDialog:false,//一键控制
        eccCtrlDialog:false,//集中器
        lightCtrlDialog:false,//单灯
        devImgDialog:false,//图例说明
        showAreaTree:true,//区域
        showPopover:false,
        isDraw:false,
        showBoxOverlay:true,
        showLightOverlay:true,
        searchBoxs:[],
        searchBoxMap:new Map(),
        box:{},
        boxId:null,
        searchPoles:[],
        searchPoleMap:new Map(),
        pole:{},
        poleId:null,
        statisticDialog:false,
        treeData: [],
        filterRegion:'',
        treeProps: {children: 'Childs', label: 'Name'},
        wsBoxs:[],
        wsPoles:[],
        poleImg:'',
        selBoxs:[],
        zoomSize:14
      }
    },
    watch: {
      filterRegion(val) {
        this.$refs.tree.filter(val)
      },
      showBoxOverlay(val){
        if(val){
          boxVectorLayer.setVisible(true)
        }else{
          boxVectorLayer.setVisible(false)
        }
      },
      showLightOverlay(val){
        if(val){
          poleVectorLayer.setVisible(true)
        }else{
          poleVectorLayer.setVisible(false)
        }
      }
    },
    computed: {
      ...mapState({
        clientHeight: state => state.comm.clientHeight,
        clientWidth: state => state.comm.clientWidth,
      })
    },
    methods: {
      //地图初始化
      mapInit() {
        map = new ol.Map({
          layers: [layerTitle,drawVector,drawVector2],
          logo: false,
          target: 'map',
          view: new ol.View({
            projection: 'EPSG:4326',//4326  3857
             zoom:14,minZoom: 4, maxZoom: 20,
          }),
        })
        let _this=this
        map.getView().on('change:resolution', function(){
          _this.zoomFun()
        })
        this.activeMarker()
        this.overlayFun()
      },
      zoomFun(){
        this.zoomSize = parseInt(map.getView().getZoom())
        //地图缩放灯杆、配电柜图标变化，active标注物的偏移位调整
        if(activeMarker.getPosition()[0]!=0&&activeMarker.getPosition()[1]!=0){
          if(!this.common.isEmpty(this.box)) {
            if(this.zoomSize<17){
              activeMarker.setOffset([-20, -50])
            }else{
              activeMarker.setOffset([-20, -72])
            }
          }else {
            if(this.zoomSize<17){
              activeMarker.setOffset([-19,-39])
            }else{
              activeMarker.setOffset([-20,-42])//用带蓝黑色背景图灯杆图标 activeMarker.setOffset([-20,-62])
            }
          }
        }
        mapMarks.map(ele => {
          let eleStyle = ele.getStyle()
          let eleImage = ele.getStyle().getImage()
          let scale = eleImage.getScale()
          if (ele.get('devtype') == 1) {
            let icon = this.getBoxIcon(ele.get('box'))
            eleStyle.setImage(new ol.style.Icon({scale: scale, src: icon}))
          }else{
            let pole = ele.get('pole')
            let bulbState = fetch.getBulbState(pole)
            let icon = this.getPoleIcon(bulbState)
            eleStyle.setImage(new ol.style.Icon({scale: scale, src: icon}))
          }
          ele.changed()
        })
      },
      //画多边形
      addInteraction() {
        let _this=this
        drawInteraction = new ol.interaction.Draw({
          source: drawVector.getSource(),
          type: 'Polygon'
        })
        drawInteraction.on('drawstart', function () {
          // drawVector.getSource().clear()
          drawing = true
        })
        drawInteraction.on('drawend', function (evt) {
          drawing = false
          _this.selectMarks(evt)
        })
        map.addInteraction(drawInteraction)
      },
      //框选后修改图标
      selectMarks(evt) {
        map.removeInteraction(drawInteraction)
        let geometry = evt.feature.getGeometry()
        // let coordinate = geometry.getCoordinates()
        mapMarks.map(r => {
          let coordinate =r.getGeometry().getCoordinates()
          if(r.get('devtype')==1&&geometry.intersectsCoordinate(coordinate)){
            let boxStyle = r.getStyle()
            boxStyle.setImage(new ol.style.Icon({
              scale: 0.7, //标注图标大小
              src: boxImgMap.get(r.get('box').Online + '_max_sel')
            }))
            r.changed()
            selBoxMarks.push(r)
            this.selBoxs.push(r.get('box'))
          }
        })
      },
      //框选、取消框选
      drawFun(){
        this.isDraw=!this.isDraw
        if(!this.isDraw){
          this.selBoxs=[]
          drawVector.getSource().clear()
          selBoxMarks.map(ele => {
            let scale=0.7
            if (this.box.BoxId == ele.get('box').BoxId){
              scale=1
            }
            let style = ele.getStyle()
            style.setImage(new ol.style.Icon({
              scale: scale, //标注图标大小
              src: boxImgMap.get(ele.get('box')['Online'] + '_max')
            }))
            ele.changed()
          })
        }else{
          this.addInteraction()
        }
      },
      //设置标注物
      setFeature(o) {
        let iconFeature = new ol.Feature({
          geometry: new ol.geom.Point(new ol.proj.fromLonLat([o.lng, o.lat], 'EPSG:4326')),
          box: o.box, pole: o.pole, devtype:o.type})
        //标注样式设置
        iconFeature.setStyle(new ol.style.Style({
          image: new ol.style.Icon({
            crossOrigin: 'anonymous',
            scale: o.scale, //标注图标大小
            src: o.icon
          })
        }))
        return iconFeature
      },
      //地图显示集中器图标
      setBoxVectorLayer(devList){
        if(boxVectorSource){
          boxVectorSource.clear()
        }
        let romeArr=[]
        devList.map(r => {
          boxMap.set('box_'+r.BoxId,r.BoxId)
          // let box={lng:r.Lng,lat:r.Lat, scale: 0.7,type:1,text:r.Name,icon:boxImgMap.get(r['Online'] + '_max'),box:r,pole:{}}
          let box={lng:r.Lng,lat:r.Lat, scale: 0.7,type:1,text:r.Name,icon:this.getBoxIcon(r),box:r,pole:{}}
          romeArr.push(this.setFeature(box))
        })
        boxVectorSource = new ol.source.Vector({
          features: romeArr
        })
        boxVectorLayer = new ol.layer.Vector({
          source: boxVectorSource
        })

        let boxfeatures = boxVectorLayer.getSource().getFeatures()
        map.addLayer(boxVectorLayer)
        mapMarks = mapMarks.concat(boxfeatures)


      },
      //地图显示灯杆图标
      setPoleVectorLayer(devList){
        if(poleVectorSource){
          poleVectorSource.clear()
        }
        let romeArr=[]
        devList.map(r => {
          poleMap.set('pole_'+r.PoleId,r.PoleId)
          let bulbState = fetch.getBulbState(r)
          let pole={lng:r.Lng,lat:r.Lat, scale: 1,type:2,text:r.PoleNo,icon:this.getPoleIcon(bulbState),box:{},pole:r}
          romeArr.push(this.setFeature(pole))
        })
        poleVectorSource = new ol.source.Vector({
          features: romeArr
        })
        poleVectorLayer = new ol.layer.Vector({
          source: poleVectorSource
        })
        map.addLayer(poleVectorLayer)
        let polefeatures = poleVectorLayer.getSource().getFeatures()
        mapMarks = mapMarks.concat(polefeatures)
      },
      getBoxIcon(box){
        let zoomSize = parseInt(map.getView().getZoom())
        if(zoomSize<17){
          if(box['Online']){
            return 'static/image/map/box.png'
          }else{
            return 'static/image/map/box_0.png'//不在线
          }
        }else{
          return boxImgMap.get(box['Online'] + '_max')
        }
      },
      getPoleIcon(bulbState){
        let zoomSize = parseInt(map.getView().getZoom())
        if(zoomSize<17&&(!bulbState.includes('2')&&!bulbState.includes('3')&&!bulbState.includes('4'))){
          if(bulbState.includes('1')){
            return 'static/image/map/pole.png'
          }else{
            return 'static/image/map/pole_0.png'
          }
        }else{
          return poleImgMap.get(bulbState + 'bulb_max')
        }
      },
      //点击图标显示三角形图标
      activeMarker() {
        activeMarker = new ol.Overlay({
          element: document.getElementById('anchor'),
          position:[0,0],
          offset:[-20,-80]
        })
        map.addOverlay(activeMarker)
      },
      //地图事件
      overlayFun() {
        let _this=this
        map.on('click', function (evt) {
          // if(_this.zoomSize<16) return
          let pixel = map.getEventPixel(evt.originalEvent)
          let feature = map.forEachFeatureAtPixel(pixel, function (feature) {
            return feature
          })
          if (feature != undefined) {
            if (feature.get('devtype')==1) {
              _this.box = feature.get('box')
              //点击某配电柜放大
              let boxfeatures = boxVectorLayer.getSource().getFeatures()
              boxfeatures.forEach(function (ele) {
                let box = ele.get('box')
                let eleImage = ele.getStyle().getImage()
                if (box.BoxId == _this.box.BoxId) {
                  selBoxMarker = ele
                  eleImage.setScale(1)
                  activeMarker.setPosition([box.Lng, box.Lat])
                  if(_this.zoomSize<17){
                    activeMarker.setOffset([-20, -50])
                  }else{
                    activeMarker.setOffset([-20, -72])
                  }
                  _this.pole = {}
                  _this.loadPoleByBoxId(box.BoxId)
                }else{
                  eleImage.setScale(0.7)
                }
                ele.changed()
                //存在点击的灯杆，鼠标移到配电箱，点击过的灯杆大小转回之前
                if (selPoleMarker) {
                  let eleImage = selPoleMarker.getStyle().getImage()
                  eleImage.setScale(1)
                  selPoleMarker.changed()
                  _this.pole={}
                }
              })
             _this.boxDialogFun()
            }
            else if(feature.get('devtype')==2){
              _this.pole = feature.get('pole')
              //点击某灯杆放大
              let polefeatures = poleVectorLayer.getSource().getFeatures()
              polefeatures.forEach(function (ele) {
                let pole = ele.get('pole')
                let eleImage = ele.getStyle().getImage()
                if (pole.PoleId == _this.pole.PoleId) {
                  selPoleMarker=ele
                  eleImage.setScale(1.3)
                  _this.poleImg=eleImage.getSrc()
                  activeMarker.setPosition([pole.Lng, pole.Lat])
                  if(_this.poleImg.includes('max')){
                    activeMarker.setOffset([-20,-42])
                  }else{
                    activeMarker.setOffset([-19,-39])
                  }
                  _this.box = {}
                }else{
                  eleImage.setScale(1)
                }
                ele.changed()
              })
              //存在点击的配电柜，鼠标移到灯杆，点击过的配电柜大小转回之前
              if (selBoxMarker) {
                let eleImage = selBoxMarker.getStyle().getImage()
                eleImage.setScale(0.7)
                selBoxMarker.changed()
                _this.box = {}
              }
             _this.poleDialogFun()
            }
          }
        })

        map.on('pointermove', function (e) {
          if(_this.zoomSize<17) return
          let pixel = map.getEventPixel(e.originalEvent)
          let feature = map.forEachFeatureAtPixel(pixel, function (feature) {
            return feature
          }) //判断当前单击处是否有要素，捕获到要素时弹出popup

          if (!feature) {
            _this.featureMouseOut()
            return
          }
          if (feature.get('devtype') == 2) {//灯杆
            let dev= feature.get('pole')
            let polefeatures = []
            if (poleVectorLayer) {
              polefeatures = poleVectorLayer.getSource().getFeatures()
            }
            polefeatures.forEach(function (ele) {
              let pole = ele.get('pole')
              let bulbState = fetch.getBulbState(ele.get('pole'))
              // let scale = 1
              if (_this.pole.PoleId == pole.PoleId) return//当前选中的灯杆忽略
              if (poleMap.get('pole_' + dev.PoleId) == pole.PoleId) {
                let scale = 1.2
                overall_lastfeature=ele
                let style = ele.getStyle()
                style.setImage(new ol.style.Icon({
                  scale: scale,
                  src: poleImgMap.get(bulbState + 'bulb_max')
                }))
                ele.changed()
              }
            })
          }
          else if (feature.get('devtype') == 1) {
            let dev = feature.get('box')
            let boxfeatures = []
            if (boxVectorLayer) {
              boxfeatures = boxVectorLayer.getSource().getFeatures()
              boxfeatures.forEach(function (ele) {
                let box = ele.get('box')
                // let scale = 0.7
                if (_this.box==undefined||_this.box.BoxId == box.BoxId) return   //当前选中的集中器忽略
                if (boxMap.get('box_' + dev.BoxId) == box.BoxId) {
                  let scale = 0.8
                  overall_lastfeature=ele
                  let eleImage = ele.getStyle().getImage()
                  eleImage.setScale(scale)
                 /* let style = ele.getStyle()
                  style.setImage(new ol.style.Icon({
                    scale: scale, //标注图标大小
                    src: boxImgMap.get(box['Online'] + '_max')//'static/image/map/box1.png'
                  }))*/
                  ele.changed()
                }
              })
            }
          }
          else{//多边形
            _this.featureMouseOut()
          }
        })
      },
      //集中器弹框
      boxDialogFun(){
        this.eccCtrlDialog = true
        this.statisticDialog = false
        this.lightCtrlDialog = false
        this.oneCtrlDialog=false
      },
      //灯杆弹框
      poleDialogFun(){
        this.lightCtrlDialog = true
        this.oneCtrlDialog=false
        this.eccCtrlDialog=false
        this.statisticDialog=false
      },
      //鼠标移开时图标变化
      featureMouseOut(){
        if(overall_lastfeature){
          let style = overall_lastfeature.getStyle().getImage()
          if(overall_lastfeature.get('devtype')==1){
            if (this.box.BoxId == overall_lastfeature.get('box').BoxId) return   //当前选中的集中器忽略
            style.setScale(0.7)
          }else{
            if (this.pole.PoleId == overall_lastfeature.get('pole').PoleId) return//当前选中的灯杆忽略
            style.setScale(1)
          }
          overall_lastfeature.changed()
          overall_lastfeature=null
        }
      },
      //根据设备获取图片
      getIcon(type,dev){
        if(type==1){
          return boxMap.get(dev['Online'] + '_max')
        }else{
          let bulbState = fetch.getBulbState(dev)
          return poleMap.get(bulbState + 'bulb_max')
        }
      },
      //数据统计
      statisticFun(){
        this.statisticDialog=!this.statisticDialog
        this.oneCtrlDialog=false
        this.eccCtrlDialog=false
        this.lightCtrlDialog=false
        this.showAreaTree = false
      },
      //一键控制
      oneCtrlFun(){
       /* if(!selBoxMarks.length){
          return this.$message.warning({showClose:true,message:'请先框选集中器'})
        }*/
        this.oneCtrlDialog=true
        this.statisticDialog=false
        this.eccCtrlDialog=false
        this.lightCtrlDialog=false
      },
      //加载配电柜所属灯杆
      loadPoleByBoxId(boxId){
        api.fetchSimple('/ViewInfo/QueryPoleById',{boxId:boxId})
            .then(r=>{
              this.setPoleVectorLayer(r.Poles)
            })
      },
      //加载灯杆、集中器
      loadBoxsPoint() {
        mapMarks = []
        api.fetchSimple('/ViewInfo/QueryDevByRegionId', {regionId: this.regionId})
            .then(r => {
              if(r!=''&&r.Poles.length){
                this.setPoleVectorLayer(r.Poles)
              }
              if(r!=''&&r.Boxs.length){
                this.setBoxVectorLayer(r.Boxs)
              }
            })
      },
      //加载责任区
      queryRegions(){
        api.fetchSimple('/ViewInfo/QueryRegionsForTree')
            .then(r=>{
              this.treeData=r
              if(this.treeData.length){
                this.regionName=this.treeData[0]['Name']
                this.regionId=this.treeData[0]['Id']
                this.loadBoxsPoint()
                this.setMapCenter([this.treeData[0].Lng,this.treeData[0].Lat])
                this.$nextTick(()=>{
                  this.$refs.tree.setCurrentKey(this.regionId)
                })
              }
            })
      },
      //定位
      setMapCenter(lnglat){
        if(Array.isArray(lnglat)){
          map.getView().setCenter(lnglat)
        }else{//一键控制 搜索定位
          map.getView().setCenter(lnglat.lnglat)
          //倒立三角
          activeMarker.setPosition(lnglat.lnglat)
          activeMarker.setOffset([-20, -72])
        }
        // map.getView().setZoom(20)
      },
      //区域树搜索
      filterNode(value, data) {
        if (!value) return true
        return data.Name.indexOf(value) !== -1
      },
      //区域树点击
      handleNodeClick(data) {
        this.regionName = data.Name
        this.regionId = data.Id
        map.getView().setCenter([data.Lng, data.Lat])
        this.$refs.tree.setCurrentKey(data.Id)
        activeMarker.setPosition([0,0])
        this.loadBoxsPoint()
      },
      //地图设备模糊搜
      searchDevs(){
        this.showPopover=true
        api.fetchSimple('/ViewInfo/SearchDevs',{value:this.searchTxt}).then(r=>{
          this.searchBoxs=r.Boxs
          this.searchPoles=r.Poles
          if(this.searchBoxs.length){
            this.searchBoxs.map(box=>{
              this.searchBoxMap.set('box_'+box.BoxId,box)
            })
          }
          if(this.searchPoles.length){
            this.searchPoles.map(pole=>{
              this.searchPoleMap.set('pole_'+pole.PoleId,pole)
            })
          }
        })
      },
      popoverBoxChange(boxId){
        this.box=this.searchBoxMap.get('box_'+boxId)
        this.searchTxt=this.box.Name
        this.setMapCenter([this.box.Lng,this.box.Lat])
        map.getView().setZoom(16)
        //倒立三角
        activeMarker.setPosition([this.box.Lng, this.box.Lat])
        if(this.zoomSize<17){
          activeMarker.setOffset([-20, -50])
        }else{
          activeMarker.setOffset([-20, -72])
        }
        //图标放大
        mapMarks.map(ele => {
          if (ele.get('devtype') == 1&&ele.get('box')['BoxId']==boxId) {
            let eleImage = ele.getStyle().getImage()
            eleImage.setScale(1)
            ele.changed()
          }
        })
        this.boxDialogFun()//弹框显示
        this.showPopover=false
      },
      popoverPoleChange(poleId){
        this.pole=this.searchPoleMap.get('pole_'+poleId)
        this.searchTxt=this.pole.PoleNo
        this.setMapCenter([this.pole.Lng,this.pole.Lat])
        map.getView().setZoom(16)
        //倒立三角
        activeMarker.setPosition([this.pole.Lng, this.pole.Lat])
        // activeMarker.setOffset([-25,-50])
        if(this.zoomSize<17){
          activeMarker.setOffset([-19,-39])
        }else{
          activeMarker.setOffset([-20,-50])
        }
        //图标放大
        mapMarks.map(ele => {
          if (ele.get('devtype') == 2&&ele.get('pole')['PoleId']==poleId) {
            let eleImage = ele.getStyle().getImage()
            eleImage.setScale(1.3)
            ele.changed()
          }
        })
        this.poleDialogFun()
        this.showPopover=false
      },
      //webSocket
      wsFun() {
        let _this=this
        let ws = new ReconnectingWebSocket(api.webSocket_url)
        ws.onmessage = function (evt) {
          let ws = JSON.parse(evt.data)
          if (ws.cmd == 'deviceStateChange') {//更新图标
            _this.wsBoxs = ws.eccs
            _this.wsPoles = ws.poles
            _this.changeBoxMarker(ws.eccs)
            _this.changePoleMarker(ws.poles,_this)
          }
        }
      },
      //监听集中器状态变化
      changeBoxMarker(boxs) {
        var boxMap = new Map()
        for (var i = 0; i < boxs.length; i++) {
          boxMap.set('box' + boxs[i].BoxId, boxs[i].Online)
        }
        var boxfeatures = []
        if (boxVectorLayer) {
          boxfeatures = boxVectorLayer.getSource().getFeatures()
        }
        boxfeatures.forEach(function (ele) {
          var boxStyle = ele.getStyle()
          var box = ele.get('box')
          let eleImage = ele.getStyle().getImage()
          let scale=eleImage.getScale()
          if (boxMap.get('box' + box.BoxId) != undefined) {
            boxStyle.setImage(new ol.style.Icon({
              scale: scale, //标注图标大小
              src: boxImgMap.get(boxMap.get('box' + box.BoxId) + '_max')
            }))
            ele.changed()
          }
        })
        if (boxVectorLayer) boxVectorLayer.getSource().refresh()
      },
      //监听灯杆状态变化
      changePoleMarker(poles,_this) {
        var poleMap = new Map()
        for (var i = 0; i < poles.length; i++) {
          poleMap.set('pole' + poles[i].Id, poles[i])
        }
        var polefeatures = []
        if (poleVectorLayer) {
          polefeatures = poleVectorLayer.getSource().getFeatures()
        }
        polefeatures.forEach(function (ele) {
          let pole = ele.get('pole')
          let poleStyle = ele.getStyle()
          let eleImage = ele.getStyle().getImage()
          let scale = eleImage.getScale()
          let p=poleMap.get('pole' + pole.PoleId)
          if (p!= undefined) {
            let bulbState = fetch.getBulbState(p)
            let src=poleImgMap.get(bulbState + 'bulb_max')
            poleStyle.setImage(new ol.style.Icon({
              scale: scale, //标注图标大小
              src:src // poleIcon
            }))
            _this.poleImg=src
            ele.changed()
          }
        })
        if (poleVectorLayer) poleVectorLayer.getSource().refresh()
      }
    },
    created() {
      drawVector.getSource().clear()
      boxImgMap=fetch.boxImgMax()
      poleImgMap=fetch.poleImgMax()
    },
    mounted() {
      let _this=this
      _this.mapInit()
      _this.queryRegions()
      _this.wsFun()
    }
  }
</script>
<style lang="stylus" rel="stylesheet/stylus">
  .map_wrapper{width:100%;height :100%;
    background:linear-gradient(270deg,rgba(16,27,84,0) 0%,rgba(0,1,43,0.95) 100%);
    .logo{width :100%;height :81px; background: url('~static/image/logo.png') no-repeat;
      .btn_back{width: 145px;height: 71px;background: url("~static/image/comm/btn_bg.png") no-repeat center;color: #BFCFEF;}
    }
    /*.search_input.el-input-group{background: url('~static/image/comm/btnSearch_border.png') no-repeat;background-size: 400px 42px;
       .el-input__inner{background:rgba(49,62,92,0.2);height: 42px !important;line-height: 42px !important;}
      .search_input.el-input-group{ background-color:#010025;color: #4C669E;}
      .search_input.el-input-group .el-input__inner{text-indent: 25px;}
    }*/
    .search_input{
      &.el-input-group{
        background:transparent url('~static/image/comm/btnSearch_border.png') no-repeat;background-size: 400px 42px;color: #4C669E;
        .el-input__inner{text-indent: 20px;height :42px;line-height 42px;}
        .ur-btn-search{height :40px;}
        .el-input-group__append{
          background :url('~static/image/comm/btnSearch.png') no-repeat;
          &:hover{background :url('~static/image/comm/btnSearch_hover.png') no-repeat;}
        }
        .el-button:hover{background :transparent !important;}
      }
    }
    .tree_input{width :400px;height 58px;background:rgba(49,62,92,0.5);border :none;
      .el-input__inner{background:none;height :58px;line-height :58px;border :none;color :#fff;font-size:20px;text-indent: 20px;}
      .el-input-group__append button{width:58px;height 58px;}
    }
    .tree_wrap{width:400px; height:600px; background:rgba(1,0,37,0.6);padding :20px 12px 27px;
      .el-icon-caret-right:before{}
    }
    .rotate180{transform: rotate(-180deg)}
    //.copyright{width:100%;height:53px;position:fixed;bottom :0;z-index:9999;background :url("~static/image/copyright.png") no-repeat center;}
    .copyrightWrapper{
      width:100%;height:53px;position:fixed;bottom :0;z-index:9999;
      background :url("~static/image/copyright_bg.png") no-repeat center;background-size:contain;
    }
    .copyright{width:100%;height:53px;background :url("~static/image/copyright3.png") no-repeat center; background-size:130px;}
    .devImgDialog li{
      width:70px;text-align :center;
      img{width:40px;margin-bottom :5px;}
      label{display:block;line-height :20px;width:70px;text-align:center;color:#6B82CB;}
    }
    .boxImgGroup li img{width:50px;}
  }
</style>
